//
//  PageContentView.swift
//  CWLiving
//
//  Created by 方正刚 on 2017/7/5.
//  Copyright © 2017年 方正刚. All rights reserved.
//

import UIKit

protocol PageContentViewDelegate : class {
    
  func pageContentView(contentView: PageContentView, progress: CGFloat, targetIndex: Int, sourceIndex: Int)
}

private let contentCell = "contentCell"

class PageContentView: UIView {

  
    var childViewControllers : [UIViewController]
    
    weak var  parentViewController : UIViewController?
    
    /// 默认不禁止响应代理
    var isForbidScrollDelegete = false
    
    /// 开始滚动的偏移
    var startOffsetX: CGFloat = 0
    
    weak var delegate: PageContentViewDelegate?
    
    lazy var collectionView : UICollectionView = { [weak self] in
    
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = (self?.bounds.size)!
        
        layout.minimumLineSpacing = 0
        
        layout.minimumLineSpacing = 0
        
        layout.scrollDirection = .horizontal
      
        let collectionV = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionV.showsHorizontalScrollIndicator = false
        collectionV.isPagingEnabled = true
        collectionV.bounces = false
        collectionV.dataSource = self
        collectionV.delegate = self
        collectionV.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCell)
        return collectionV

    }()
    
    init(frame: CGRect, childVCs: [UIViewController], parentVC: UIViewController?) {
        self.childViewControllers = childVCs
        self.parentViewController = parentVC
        
        super.init(frame: frame)
        // 设置UI
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

}


extension PageContentView {
    
    //把子控制器添加到父控制中
    func setupUI() {
        
        for childVC in childViewControllers {
            parentViewController?.addChildViewController(childVC)
        }
        
        addSubview(collectionView)
        
        collectionView.frame = bounds
    }
    
  
}




// MARK: - collectionView的数据源方法
extension PageContentView : UICollectionViewDataSource {
   
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childViewControllers.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCell, for: indexPath)
        
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        let childVC = childViewControllers[indexPath.row]
        
        childVC.view.frame = cell.contentView.bounds
        
        cell.contentView.addSubview(childVC.view)
        
        return cell
    }
    
}

// MARK: - collectionView的代理方法
extension PageContentView : UICollectionViewDelegate {
    
    
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        isForbidScrollDelegete = false
        
        startOffsetX = scrollView.contentOffset.x
    }
    
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
      
        if isForbidScrollDelegete { return }
        // 计算进度
        var progress: CGFloat = 0
        // 目标item的下标
        var targetIndex: Int = 0
        
        var sourceIndex: Int = 0
        
        // 判断滚动方向
        if scrollView.contentOffset.x > startOffsetX { // 向左滚动
            // 计算进度
            progress = scrollView.contentOffset.x / bounds.width - floor(scrollView.contentOffset.x / bounds.width)
            // 初始item的下标
            sourceIndex = Int(scrollView.contentOffset.x / bounds.width)
            // 目标item的下标
            targetIndex = (sourceIndex + 1) >= childViewControllers.count ? (childViewControllers.count - 1) : (sourceIndex + 1)
            
            if scrollView.contentOffset.x - startOffsetX >= bounds.size.width{
                progress = 1
                targetIndex = sourceIndex
            }
            
        }else { //向右侧滚动
            
            // 计算进度
            progress = 1 - scrollView.contentOffset.x / bounds.width + floor(scrollView.contentOffset.x / bounds.width)
            
            // 目标item的下标
            targetIndex = Int(scrollView.contentOffset.x / bounds.width)
            
            sourceIndex = (targetIndex + 1) >= childViewControllers.count ? childViewControllers.count - 1 : (targetIndex + 1)
       }
      
        
        
     self.delegate?.pageContentView(contentView: self, progress: progress, targetIndex: targetIndex, sourceIndex: sourceIndex)
        
    }
    
}


extension PageContentView {
    
    func setCurrentIndex(currentIndex: Int) {
        
        
        /// 禁止响应代理
        isForbidScrollDelegete = true
        
        
        /// 执行滚动偏移
        let offsetX = CGFloat(currentIndex) * bounds.width
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
        
    }
}




